﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace S.Eartag.Infrastructure
{
    public class BaseRepository<T>: IBaseRepository<T> where T : class
    {
        private readonly EFDbContext db;

        public BaseRepository(EFDbContext db)
        {
            this.db = db;
        }

        public async Task<IQueryable<T>> All()
        {
            return await Task.FromResult(db.Set<T>().AsQueryable());
        }

        public async Task<int> Create(T model)
        {
            await db.AddAsync(model);
            return await db.SaveChangesAsync();
        }

        public async Task<int> Delete(int id)
        {
            DbSet<T> dbset = db.Set<T>();
            var res = dbset.Find(id);
            dbset.Remove(res);
            return await db.SaveChangesAsync();
        }

        public async Task<int> DeleteAll(List<T> values)
        {
            return await db.SaveChangesAsync();
        }

        public async Task<T> Get(int id)
        {
            DbSet<T> dbset = db.Set<T>();
            return await dbset.FindAsync(id);
        }

        public async Task<T> GetInfo(Expression<Func<T, bool>> expression)
        {
            DbSet<T> dbset = db.Set<T>();
            return await dbset.FirstOrDefaultAsync(expression);
        }

        public async Task<List<T>> GetValues(Expression<Func<T, bool>> expression)
        {
            DbSet<T> dbset = db.Set<T>();
            return await dbset.Where(expression).ToListAsync();
        }

        public async Task<int> Update(T model)
        {

            DbSet<T> dbset = db.Set<T>();
            dbset.Update(model);
            return await db.SaveChangesAsync();
        }

        public async Task<int> UpdateAll(List<T> info)
        {
            db.UpdateRange(info);
            return await db.SaveChangesAsync();
        }
    }
}
